<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="filters.keyword" placeholder="请输入部门名称或者编号"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="searchBycon">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="emps" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="60">
			</el-table-column>
      <el-table-column prop="username" label="姓名" width="120" >
      </el-table-column>
			<el-table-column prop="email" label="邮箱" width="120" >
			</el-table-column>
			<el-table-column prop="phone" label="电话" width="100"  >
			</el-table-column>
			<el-table-column prop="salt" label="salt" width="100" >
			</el-table-column>
			<el-table-column prop="password" label="密码" width="120" >
			</el-table-column>
      <el-table-column prop="age" label="年龄" width="120" >
      </el-table-column>
			<el-table-column prop="state" label="启用状态" min-width="180" >
        <template scope="scope">
          <div>
            <el-link type="success" v-if="scope.row.state==1">激活</el-link>
            <el-link type="danger" v-if="scope.row.state==0">禁用</el-link>
          </div>
        </template>
			</el-table-column>
      <el-table-column prop="departmentId" label="department_id" width="100" >
      </el-table-column>
      <el-table-column prop="logininfoId" label="logininfo_id" width="120" >
      </el-table-column>
      <el-table-column prop="shopId" label="shop_id" width="120" >
      </el-table-column>
			<el-table-column label="操作" width="150">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" :current-page="currentpage" @click="handleDel(scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="deleteAll" :current-page="currentpage" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="pageSize"
                     :total="total"
                     style="float:right;">
			</el-pagination>
		</el-col>

		<!--&lt;!&ndash;编辑界面&ndash;&gt;
		<el-dialog title="编辑" :visible.sync="editFormVisible" :close-on-click-modal="false">
			<el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
				<el-form-item label="姓名" prop="name">
					<el-input v-model="editForm.name" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="性别">
					<el-radio-group v-model="editForm.sex">
						<el-radio class="radio" :label="1">男</el-radio>
						<el-radio class="radio" :label="0">女</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="年龄">
					<el-input-number v-model="editForm.age" :min="0" :max="200"></el-input-number>
				</el-form-item>
				<el-form-item label="生日">
					<el-date-picker type="date" placeholder="选择日期" v-model="editForm.birth"></el-date-picker>
				</el-form-item>
				<el-form-item label="地址">
					<el-input type="textarea" v-model="editForm.addr"></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="editFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
			</div>
		</el-dialog>-->

		<!--新增界面-->
		<el-dialog :title='title' :visible.sync="addFormVisible" :close-on-click-modal="false">
			<el-form :model="addForm" label-width="80px" :rules="addFormRules" ref="addForm">
				<el-form-item label="员工姓名" prop="username">
					<el-input v-model="addForm.username" auto-complete="off"></el-input>
				</el-form-item>
        <el-form-item label="员工邮箱" prop="email">
          <el-input v-model="addForm.email" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="员工电话" prop="phone">
          <el-input v-model="addForm.phone" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="员工salt" prop="salt">
          <el-input v-model="addForm.salt" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model="addForm.age" auto-complete="off"></el-input>
        </el-form-item>
				<el-form-item label="状态">
					<el-radio-group v-model="addForm.state">
						<el-radio class="radio" :label="0">启用</el-radio>
						<el-radio class="radio" :label="-1">禁用</el-radio>
					</el-radio-group>
				</el-form-item>
        <el-form-item label="部门经理">
          <el-select v-model="addForm.manager.id" placeholder="请选择">
            <el-option
                v-for="item in emps"
                :key="item.id"
                :label="item.username"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上级部门">
          <el-cascader v-model="addForm.parent"
              :options="tree"
              :props="{ checkStrictly: true,value:'id',label:'name' }"
              clearable></el-cascader>
        </el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="addFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>
	//import util from '../../common/js/util'
	//import NProgress from 'nprogress'
	//import { getUserListPage, removeUser, batchRemoveUser, editUser, addUser } from '../../api/api';

	export default {
		data() {
			return {
				filters: {
					keyword: ''
				},
				emps: [],
				total: 0,
        pageSize:3,
				currentpage: 1,
				listLoading: false,
				sels: [],//列表选中列
        tree:[],
        title:'',
				editFormVisible: false,//编辑界面是否显示
				editLoading: false,
				editFormRules: {
					name: [
						{ required: true, message: '请输入姓名', trigger: 'blur' }
					],

				},
			/*	//编辑界面数据
				editForm: {
					id: 0,
					name: '',
					sex: -1,
					age: 0,
					birth: '',
					addr: ''
				},
*/
				addFormVisible: false,//新增界面是否显示
				addLoading: false,
				addFormRules: {
					name: [
						{ required: true, message: '请输入部门名称', trigger: 'blur' }
					],
          sn: [
            { required: true, message: '请输入部门编号', trigger: 'blur' }
          ]
				},

				//新增界面数据
				addForm: {
				  sn:'',
					name: '',
					dirPath:'',
					state:0,
					manager: {
				    id:''
          },
					parent: null
				}

			}
		},
		methods: {
      searchBycon(){
        this.currentpage=1
        this.getDepts()
      },

      //获取员工数据
      /*loadEmployees(){
          this.$http.get('/emp').then((res)=>{
           // console.log(res.data)
            this.emps=res.data;
          }).catch()
      },*/
      loadTree(){
        this.$http.get('/emp/tree').then((res)=>{
          // console.log(res.data)
          this.tree=res.data;
        }).catch()
      },
			//性别显示转换

			handleCurrentChange(val) {
				this.currentpage = val;
				this.getDepts();
			},

			//获取用户列表
			getDepts() {
				let para = {
					currentpage: this.currentpage,
					pageSize: this.pageSize,
          keyword:this.filters.keyword
				};
				this.listLoading = false;
				//NProgress.start();
				this.$http.post("/emp",para).then((res)=>{
          console.log(res)
          this.emps = res.data.rows
          this.total = res.data.totals
        }).catch(()=>{

        })
			},
			//删除
			handleDel: function (row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();

					this.$http.delete("/emp/"+row.id).then((res) => {
						this.listLoading = false;
						//NProgress.done();
            let {message,success} = res.data
						this.$message({
							message: message,
							type: success?'success':'error'
						});
						this.currentpage=1;
						this.getDepts();
					});
				}).catch(() => {

				});
			},
			//显示编辑界面
			handleEdit: function (index, row) {
        /*this.loadEmployees();
        this.loadTree();
				this.addFormVisible = true;
				this.title='编辑';
				this.addForm = Object.assign({}, row);
				let path = this.addForm.dirPath.split("/");
				let parr=[];
				for(let i=0;i<path.length-1;i++){
          parr.push(parseInt(path[i]))
        };
				this.addForm.parent=parr;*/
        //拉取数据
        this.loadEmployees();
        this.loadTree();

        this.title = "编辑";
        this.addFormVisible = true;
        this.addForm = Object.assign({}, row);
        //this.addForm.parent=[2,9]
       // 上级部门回显：  读出dirPath /3/54/55 a)
        //console.log(row)
        let path = this.addForm.dirPath.split("/");// ["","3","54","55"]
        let parr = [];
        // 获取除自身id添加到数组（构造一个整型数组）
        for (let i = 1; i < path.length - 1; i++) {
          parr.push(parseInt(path[i]));
        }
        //级联组件根据提供设置数组就 回显状态
        this.addForm.parent = parr;
			},
			//显示新增界面
			handleAdd: function () {
				this.addFormVisible = true;
				this.loadEmployees();
				this.loadTree();
				this.title='新增';
				this.addForm = {
          sn:'',
          name: '',
          dirPath:'',
          state:0,
          manager: {
            id:''
          },
          parent: null
				};
			},
			//编辑
		/*	editSubmit: function () {
				this.$refs.editForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.editLoading = true;
							//NProgress.start();
							let para = Object.assign({}, this.editForm);
							para.birth = (!para.birth || para.birth == '') ? '' : util.formatDate.format(new Date(para.birth), 'yyyy-MM-dd');
							editUser(para).then((res) => {
								this.editLoading = false;
								//NProgress.done();
								this.$message({
									message: '提交成功',
									type: 'success'
								});
								this.$refs['editForm'].resetFields();
								this.editFormVisible = false;
								this.getDepts();
							});
						});
					}
				});
			},*/
			//新增
			addSubmit: function () {
				this.$refs.addForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
              //console.log(this.addForm);
              this.addLoading = false;
              //NProgress.start();
              //para克隆表单数据
              let para = Object.assign({}, this.addForm);
              let arr = para.parent;
              if(arr!=null){
                let pid = arr[arr.length-1];
                para.parent={
                  id:pid
                }
              }else{
                para.parent=null;
              }

              this.$http.put('/emp',para).then((res) => {
                console.log(res)
                this.addLoading = false;
                //NProgress.done();
                let {message,success} = res.data
                this.$message({
                  message: message,
                  type: success?'success':'error'
                });

                //重置验证,关闭编辑框
                this.$refs['addForm'].resetFields();
                this.addFormVisible = false;
                this.currentpage=1;
                this.getDepts();
              });
						});
					}
				});
			},
			selsChange: function (sels) {
				this.sels = sels;
				//console.log("++++++"+sels)
			},
			//批量删除
			deleteAll: function () {
				var ids = this.sels.map(item => item.id);
        //console.log("++++"+ids);
        this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();
					//let para = { ids: ids };
					this.$http.patch("/emp",ids).then((res) => {
						this.listLoading = false;
						//NProgress.done();
            let {success,message} = res.data;
						this.$message({
							message: message,
							type: success?'success':'error'
						});
						this.currentpage=1;
						this.getDepts();
					});
				}).catch(() => {

				});
			}
		},
		mounted() {
			this.getDepts();
		},
	}

</script>

<style scoped>

</style>